package com.jinsilu.freight.ui.activity;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ObjectUtils;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.jinsilu.freight.R;
import com.jinsilu.freight.aop.SingleClick;
import com.jinsilu.freight.common.MyVBActivity;
import com.jinsilu.freight.databinding.ActivityUploadDrivingLicenseBinding;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.helper.ShowImageHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.GetDrivingLicenseApi;
import com.jinsilu.freight.http.request.OCRApi;
import com.jinsilu.freight.http.request.UpdateImageApi;
import com.jinsilu.freight.http.request.VerifyDrivingLicenseApi;
import com.jinsilu.freight.http.response.DrivingLicenseBean;
import com.jinsilu.freight.http.response.FileBean;
import com.jinsilu.freight.http.response.OCRDriveBean;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.dialog.DateDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 上传驾驶证
 *
 * @author yangyang
 * @time 2020-11-11 17:35
 */
public class UploadDrivingLicenseActivity extends MyVBActivity<ActivityUploadDrivingLicenseBinding> {

    private final String TAG = getClass().getName();
    private int mCurrentSelectIndex; // 当前选择上传的图片条目索引

    private String frontImage;
    private String backImage;

    private DrivingLicenseBean mDrivingLicenseBean;

    @Override
    protected void initView() {
//        binding.tvNotificationTips.setVisibility(View.VISIBLE);
//        binding.tvNotificationTips.setText("拍摄图片时，请保持画面文字的清晰。");

        setOnClickListener(
                binding.ivDrivingLicense,
                binding.ivDrivingLicenseCopy,
                binding.tvBtnSubmitCertificate,
                binding.tvExpirationDate,
                binding.tvReviewDate
        );

    }

    @Override
    protected void initData() {
        getDrivingLicenseStatus();
        initStep();
    }

    private void initStep() {
        binding.layoutCertification.tvCertificationTips.setText("请使用本人身份信息进行认证，若使用他人身份认证并接单，将造成运费无法提现");
        binding.layoutCertification.stepView
                .go(MTLConstants.STEP_TWO, false);
    }

    /**
     * 获取驾驶证状态
     */
    private void getDrivingLicenseStatus() {
        EasyHttp.get(this)
                .api(new GetDrivingLicenseApi())
                .request(new HttpCallback<HttpData<DrivingLicenseBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<DrivingLicenseBean> data) {
                        mDrivingLicenseBean = data.getData();
                        setCertificateStatus(mDrivingLicenseBean);
                    }
                });
    }

    private void setCertificateStatus(DrivingLicenseBean drivingLicenseBean) {
        // -2---未认证，-1---待审核，0---失败，1---成功
        switch (drivingLicenseBean.getDriversLicenseCertificationStatus()) {
            case -2: // 未认证
                break;
            case 0: // 认证失败
//                binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approved_rejected_ic);
//                binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
//                binding.layoutCertification.tvCertificationStatus.setText("审核未通过");
//                binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                binding.layoutCertification.tvCertificationTips.setText(TextUtils.isEmpty(drivingLicenseBean.getOpinion()) ? "" : drivingLicenseBean.getOpinion());
                setContentData(drivingLicenseBean);
                break;
            case 1: // 认证成功
//                binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approved_ic);
//                binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
//                binding.layoutCertification.tvCertificationStatus.setText("审核通过");
//                binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                disableClicked(getString(R.string.tips_approved));
                setContentData(drivingLicenseBean);
                break;
            case -1: // 提交全部认证资料 认证中
//                binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approving_ic);
//                binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
//                binding.layoutCertification.tvCertificationStatus.setText("审核中");
//                binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                disableClicked(getString(R.string.tips_approving));
                setContentData(drivingLicenseBean);
                break;
            default:
                break;
        }
    }

    /**
     * 设置不允许点击
     */
    private void disableClicked(String tips) {
        binding.ivDrivingLicense.setEnabled(false);
        binding.ivDrivingLicenseCopy.setEnabled(false);
        binding.etQuasiDrivingModels.setEnabled(false);
        binding.tvExpirationDate.setEnabled(false);
        binding.tvReviewDate.setEnabled(false);

        binding.layoutCertification.stepView.done(true);

        binding.layoutCertification.tvCompleteCanTakeOrder.setText(tips);
        binding.layoutCertification.tvCertificationTips.setVisibility(View.GONE);

        binding.tvDrivingLicenseTips.setVisibility(View.GONE);
        binding.tvDrivingLicenseCopyTips.setVisibility(View.GONE);
    }

    /**
     * 数据回填
     *
     * @param drivingLicenseBean 驾驶证认证信息
     */
    private void setContentData(DrivingLicenseBean drivingLicenseBean) {
        frontImage = drivingLicenseBean.getDriverLicenseFrontUrl();
        backImage = drivingLicenseBean.getDriverLicenseReverseUrl();
        if (!TextUtils.isEmpty(drivingLicenseBean.getDriverLicenseFrontUrl()))
            ShowImageHelper.showNormal(this, drivingLicenseBean.getDriverLicenseFrontUrl(), binding.ivDrivingLicense);
        if (!TextUtils.isEmpty(drivingLicenseBean.getDriverLicenseReverseUrl()))
            ShowImageHelper.showNormal(this, drivingLicenseBean.getDriverLicenseReverseUrl(), binding.ivDrivingLicenseCopy);
        binding.etQuasiDrivingModels.setText(drivingLicenseBean.getQuasiDrivingType());
        binding.tvExpirationDate.setText(drivingLicenseBean.getValidityEndDate());
        binding.tvReviewDate.setText(drivingLicenseBean.getReviewDate());
        binding.tvBtnSubmitCertificate.setEnabled(true);
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        if (v == binding.tvExpirationDate) {
            showDateDialog(0);
        }else if (v == binding.tvReviewDate) {
            showDateDialog(1);
        } else if (v == binding.ivDrivingLicense) {
            mCurrentSelectIndex = 0;
//            startImageSelectActivity(0);、
            showTipsDialog();
        } else if (v == binding.ivDrivingLicenseCopy) {
            mCurrentSelectIndex = 1;
//            startImageSelectActivity(1);
            showTipsDialog();
        } else if (v == binding.tvBtnSubmitCertificate) {
            if (null == mDrivingLicenseBean) {
                toast(R.string.error_certification_failed_with_network);
                return;
            }
            switch (mDrivingLicenseBean.getDriversLicenseCertificationStatus()) {
                // -2---未认证，-1---待审核，0---失败，1---成功
                case -2: // 未认证
                case 0: // 认证失败
                    submitInfo();
                    break;
                case -1: // -待审核
                case 1: // 认证成功
                    toNextSteps();
                    break;
                default:
                    break;
            }
        }
    }

    private void toNextSteps() {
        startActivity(UploadQualificationCertificateActivity.class);
    }

    /**
     * 驾驶证认证
     */
    private void submitInfo() {
        if (TextUtils.isEmpty(frontImage)) {
            toast("请上传驾驶证正本");
            return;
        }
        if (TextUtils.isEmpty(backImage)) {
            toast("请上传驾驶证副本");
            return;
        }

        String valid = binding.tvExpirationDate.getText().toString().trim();
        if (TextUtils.isEmpty(valid)) {
            toast("请选择有效期止");
            return;
        }

        String reviewDate = binding.tvReviewDate.getText().toString().trim();

        EasyHttp.post(this)
                .api(new VerifyDrivingLicenseApi()
                        .setDrivingFrontUrl(frontImage)
                        .setDrivingReverseUrl(backImage)
                        .setAddress(mDrivingLicenseBean.getAddress())
                        .setDrawTime(mDrivingLicenseBean.getDrawTime())
                        .setDriverLicense(mDrivingLicenseBean.getDriverLicense())
                        .setIssuingAuthority(mDrivingLicenseBean.getIssuingAuthority())
                        .setQuasiDrivingType(mDrivingLicenseBean.getQuasiDrivingType())
                        .setValidityStartDate(mDrivingLicenseBean.getValidityStartDate())
                        .setValidityEndDate(valid)
                        .setReviewDate(reviewDate)
                )
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
//                        setResult(RESULT_OK);
//                        finish();
                        toNextSteps();
                    }

                    @Override
                    public void onFail(Exception e) {
                        CommonHelper.toastErrorMsg(e, getString(R.string.plz_reupload_driving_image));
                    }
                });
    }

    /**
     * 启动图片选择
     */
    private void startImageSelectActivity(int index) {
        ImageSelectVBActivity.start(this, new ImageSelectVBActivity.OnPhotoSelectListener() {

            @Override
            public void onSelected(File file) {
//                File file = CommonHelper.getFileFromUri(data);
                uploadImage(file);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    private void uploadImage(File file) {
        // 上传文件
        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setImage(file))
                .request(new HttpCallback<HttpData<FileBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<FileBean> data) {
//                        FileUtils.delete(file);
                        String imgUrl = data.getData().getUrl();
                        if (mCurrentSelectIndex == 0) {
//                            frontImage = imgUrl;
//                            ShowImageHelper.showNormal(UploadDrivingLicenseActivity.this, imgUrl, binding.ivDrivingLicense);
                            ocr(MTLConstants.DRIVE_FRONT, imgUrl);
                        } else {
//                            backImage = imgUrl;
//                            ShowImageHelper.showNormal(UploadDrivingLicenseActivity.this, imgUrl, binding.ivDrivingLicenseCopy);
                            ocr(MTLConstants.DRIVE_BACK, imgUrl);
                        }
                    }
                });
    }

    /**
     * orc 识别
     *
     * @param type   类型【1身份证人像面；2身份证国徽面；3驾驶证正页；4驾驶证副页；5行驶证正页；6行驶证副页；7车辆道路运输证】
     * @param imgUrl 图片地址
     */
    private void ocr(String type, String imgUrl) {
        EasyHttp.post(this)
                .api(new OCRApi()
                        .setType(type)
                        .setUrl(imgUrl)
                )
                .request(new HttpCallback<HttpData<OCRDriveBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<OCRDriveBean> data) {
                        OCRDriveBean ocrDriveBean = data.getData();
                        if (ObjectUtils.isEmpty(ocrDriveBean)) {
                            toast(R.string.plz_reupload_driving_image);
                            return;
                        }
                        if (mCurrentSelectIndex == 0) {
                            mDrivingLicenseBean.setDriverLicenseFrontUrl(imgUrl);
                            mDrivingLicenseBean.setAddress(ocrDriveBean.getAddress());
                            mDrivingLicenseBean.setDrawTime(ocrDriveBean.getIssueDate());
                            mDrivingLicenseBean.setDriverLicense(ocrDriveBean.getNumber());
                            mDrivingLicenseBean.setIssuingAuthority(ocrDriveBean.getIssuingAuthority());
                            mDrivingLicenseBean.setQuasiDrivingType(ocrDriveBean.getClassX());
                            mDrivingLicenseBean.setValidityStartDate(ocrDriveBean.getValidFrom());
                            if (MTLConstants.LONG_TIME.equals(ocrDriveBean.getValidTo())) { // @dsz @wyh
                                mDrivingLicenseBean.setValidityEndDate(MTLConstants.LONG_TIME_DEFAULT);
                            } else {
                                mDrivingLicenseBean.setValidityEndDate(ocrDriveBean.getValidTo());

                            }
                        } else if (mCurrentSelectIndex == 1) {
                            mDrivingLicenseBean.setDriverLicenseReverseUrl(imgUrl);
                            if(!TextUtils.isEmpty(ocrDriveBean.getAddress())){
                                mDrivingLicenseBean.setAddress(ocrDriveBean.getAddress());
                            }

                            if(!TextUtils.isEmpty(ocrDriveBean.getIssuingAuthority())){
                                mDrivingLicenseBean.setIssuingAuthority(ocrDriveBean.getIssuingAuthority());
                            }

                        }
                        setContentData(mDrivingLicenseBean);
                    }

                    @Override
                    public void onFail(Exception e) {
                        toast(R.string.plz_reupload_driving_image);
                    }
                });
    }

    private BaseDialog tipsDialog;

    private void showTipsDialog() {
        // 自定义对话框
        if (null == tipsDialog) {
            tipsDialog = new BaseDialog.Builder(this)
                    .setContentView(R.layout.dialog_certificate_tips)
                    .setAnimStyle(BaseDialog.ANIM_SCALE)
                    //.setText(id, "我是预设置的文本")
                    .setGravity(Gravity.BOTTOM)
                    .setOnClickListener(R.id.tv_know, (BaseDialog.OnClickListener<TextView>) (dialog, view) ->
                            {
//                                showMenuDialog();
                                startImageSelectActivity(-1);
                                dialog.dismiss();
                            }

                    )
                    .show();
        } else {
            tipsDialog.show();
        }
    }

    private BaseDialog expirationDialog;

    private void showDateDialog(int type) {
        // 日期选择对话框
        if (null == expirationDialog) {
            expirationDialog = new DateDialog.Builder(this)
                    .setTitle(getString(R.string.date_title))
                    // 确定按钮文本
                    .setConfirm(getString(R.string.common_confirm))
                    // 设置 null 表示不显示取消按钮
                    .setCancel(getString(R.string.common_cancel))
                    // 设置日期
                    //.setDate("2018-12-31")
                    //.setDate("20181231")
                    //.setDate(1546263036137)
                    // 设置年份
                    //.setYear(2018)
                    // 设置月份
                    //.setMonth(2)
                    // 设置天数
                    //.setDay(20)
                    // 不选择天数
                    //.setIgnoreDay()
                    .setListener(new DateDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, int year, int month, int day) {
//                            toast(year + getString(R.string.common_year) + month + getString(R.string.common_month) + day + getString(R.string.common_day));
                            // 如果不指定时分秒则默认为现在的时间
//                            Calendar calendar = Calendar.getInstance();
//                            calendar.set(Calendar.YEAR, year);
                            // 月份从零开始，所以需要减 1
//                            calendar.set(Calendar.MONTH, month - 1);
//                            calendar.set(Calendar.DAY_OF_MONTH, day);
//                            toast("时间戳：" + calendar.getTimeInMillis());
                            //toast(new SimpleDateFormat("yyyy年MM月dd日 kk:mm:ss").format(calendar.getTime()));
                            if(type == 0){
                                binding.tvExpirationDate.setText(String.format("%s-%s-%s", year, month, day));
                            }else if(type == 1){
                                binding.tvReviewDate.setText(String.format("%s-%s-%s", year, month, day));
                            }

                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {

                        }
                    })
                    .show();
        } else {
            expirationDialog.show();
        }
    }


}